package cn.suimg.bilibili.bean;

import javolution.io.Struct;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;

public class Package extends Struct {

    private Signed32 totalLength = new Signed32();
    private Signed16 headerLength = new Signed16();
    private Signed16 protocol = new Signed16();
    private Signed32 option = new Signed32();
    private Signed32 sequence = new Signed32();

    private byte[] body;

    @Override
    public boolean isPacked() {
        return true;
    }

    @Override
    public ByteOrder byteOrder() {
        return ByteOrder.BIG_ENDIAN;
    }


    private void setTotalLength(int totalLength) {
        this.totalLength.set(totalLength);
    }


    private void setHeaderLength(int headerLength) {
        this.headerLength.set((short)headerLength);
    }


    private void setProtocol(int protocol) {
        this.protocol.set((short)protocol);
    }


    private void setOption(int option) {
        this.option.set(option);
    }


    private void setSequence(int sequence) {
        this.sequence.set(sequence);
    }

    public Package(Option option,String body){
        this(option,body.getBytes());
    }

    public Package(Option option,byte[] bytes){
        int headerLength = 16;
        int bodyLength = bytes.length;
        setTotalLength(headerLength + bodyLength);
        setHeaderLength(headerLength);
        setOption(option.getData());
        setProtocol(1);
        setSequence(1);
        this.body=bytes;
    }

    public byte[] getBytes() throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        this.write(outputStream);
        outputStream.write(this.body);
        return outputStream.toByteArray();
    }


}
